package com.mine.jzh3.oss.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mine.jzh.SysEnum;
import com.mine.jzh.mapper.SysEnumMapper;
import com.mine.jzh3.oss.entity.AliOSSConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * 阿里云OSS配置服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AliOSSConfigService {
    private static final String REDIS_KEY = "oss:config:ali";
    private static final Duration CACHE_DURATION = Duration.ofHours(24);

    private final StringRedisTemplate redisTemplate;
    private final SysEnumMapper sysEnumMapper;
    private final ObjectMapper objectMapper;

    /**
     * 配置是否在缓存中
     */
    public boolean exitInCache() {
        return redisTemplate.hasKey(REDIS_KEY);
    }

    /**
     * 从数据库加载配置
     */
    public AliOSSConfig loadConfigFromDB() {
        try {
            SysEnum sysEnum = sysEnumMapper.selectByDictCodeAndCode("OSS_CONFIG", "ALI");
            AliOSSConfig config = new AliOSSConfig();
            config.setAccessKey(sysEnum.getRemark1());
            config.setSecretKey(sysEnum.getRemark2());
            config.setEndpoint(sysEnum.getRemark3());
            config.setBucketName(sysEnum.getRemark4());
            config.setDomain(sysEnum.getRemark5());
            return config;
        } catch (Exception e) {
            log.error("从数据库加载阿里云OSS配置失败", e);
            return null;
        }
    }

    /**
     * 更新配置到缓存
     */
    public void updateConfigCache(AliOSSConfig config) {
        try {
            String jsonConfig = objectMapper.writeValueAsString(config);
            redisTemplate.opsForValue()
                    .set(REDIS_KEY, jsonConfig, CACHE_DURATION);
            log.info("阿里云OSS配置已更新到缓存");
        } catch (Exception e) {
            log.error("更新阿里云OSS配置到缓存失败", e);
        }
    }

    /**
     * 获取存储配置
     */
    public AliOSSConfig getStorageConfig() {
        AliOSSConfig config = loadConfigFromDB();
        if (config == null || !config.isValid()) {
            log.error("从数据库获取的阿里云OSS配置无效");
            throw new IllegalStateException("无法获取有效的阿里云OSS配置");
        }

        // 3. 更新缓存
        updateConfigCache(config);
        return config;
    }
}
